package socks;

public class EncodeUtil {
	
	/**
	 * 必须少于127
	 * @param seed
	 * @return
	 */
	private static int genSeed( int seed) {
		//return 10;
		return ( seed + 55) % 70;
	}
	
	public static int encode(int b, int seed ) {
		if( b >= 0 && b <= 127 ) {
			return (b + genSeed(seed) ) % 128;
		}
		return b;
	}
	
	public static int decode(int b , int seed) {
		if( b >= 0 && b <= 127 ) {
			return (128 + b - genSeed(seed) )%128;
		}
		return b;
		
	}
	
	public static byte encode(byte b , int seed) {
		return (byte) encode( (int)b,  seed );
		
	}
	
	public static byte decode(byte b , int seed) {
		return (byte)decode( (int)b ,  seed);
		
//		if( b >= 0 && b <= 127 ) {
//			if( b == 0 ) {
//				return 127;
//			} else {
//				return (byte)(b -1);
//			}
//		}
//		return b;
		
	}
	
	public static void encode(byte[] bs ,int offset, int length, int seed) {
		for( int i= 0; i< length; i++) {
			bs[offset + i] = encode( bs[offset + i] , seed + i);
		}
	}
	
	public static void decode(byte[] bs ,int offset, int length , int seed) {
		for( int i= 0; i< length; i++) {
			bs[offset + i] = decode( bs[offset + i] , seed + i);
		}
	}
	
	public static void testNorByte() {
		for ( int seed =0; seed < 100000; seed++ ) {
			for ( int i = 0; i< 255; i++ ) {
				decode( encode((int) i , seed) ,seed) ;
//				if( i != decode( encode((int) i , seed) ,seed)  ) {
//					System.out.println( "error:" + decode( encode((byte) i , 10) ,10)   + ";" + i );
//				} else {
//					//System.out.println( "OK:" + decode( encode((byte) i , 10) ,10)   + ";" + i );
//				}
			}
		}
	}
	
	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		testNorByte();
		System.out.println( "ok : " + ( 523 % 14) );
		//System.out.println( ~ b );
	}
}
